package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 点击聊一聊后添加好友
     *
     * @param loginUserId
     * @param userId
     */
    @Override
    public void makeFriends(Long loginUserId, Long userId) {

        //添加好友 （登录用户与佳人）
        Query query = new Query(Criteria.where("userId").is(loginUserId).and("friendId").is(userId));

        Friend friend = new Friend();
        friend.setCreated(System.currentTimeMillis());
        friend.setUserId(loginUserId);
        friend.setFriendId(userId);
        if (!mongoTemplate.exists(query, Friend.class)) {
            mongoTemplate.insert(friend);
        }
        //添加好友 （佳人与登录用户）
        Query queryFriend = new Query(Criteria.where("userId").is(userId).and("friendId").is(loginUserId));
        if(!mongoTemplate.exists(queryFriend,Friend.class)){
            friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(userId);
            friend.setFriendId(loginUserId);
            mongoTemplate.insert(friend);
        }

    }

    /**
     *
     * 查询联系人列表
     * @param loginUserId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(Long loginUserId, Long page, Long pageSize) {

        //构建条件
        Query query = new Query(Criteria.where("userId").is(loginUserId));

        //查询总数
        long count = mongoTemplate.count(query, Friend.class);

        List<Friend> friendList = new ArrayList<>();
        if(count>0){
            //设置分页参数
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            //按照时间降序
            query.with(Sort.by(Sort.Order.desc("created")));
            //获取结果集
            friendList = mongoTemplate.find(query, Friend.class);
        }
        return PageResult.pageResult(page,pageSize,friendList,count);
    }
}
